<?php

namespace support\Middleware;

use app\middleware\ReflectionException;
use support\exception\BusinessException;
use support\Model\ActionLogModel;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class HttpDebug implements MiddlewareInterface
{
    /**
     * @param Request $request
     * @param callable $handler
     * @return Response
     * @throws ReflectionException|BusinessException
     */
    public function process(Request $request, callable $handler): Response
    {
        $now = date('Y-m-d H:i:s');
        // 日志数据
        $data = [
            'username' => '管理员',
            'plugin' => $request->plugin,
            'module' => $request->app,
            'controller' => $request->controller,
            'action' => $request->action,
            'method' => $request->method(),
            'url' => $request->fullUrl(), // 获取完成URL
            'param' => $request->all() ? json_encode($request->all()) : '',
            'title' => '操作日志',
            'type' => 3,
            'content' => '',
            'ip' => $request->getRemoteIp(),
            'user_agent' => $request->header('HTTP_USER_AGENT') ?: '1',
            'create_time' => time(),
        ];
        $response = $handler($request);
        $data['content'] = $response->rawBody();
        try {
            if (strpos($data['controller'], 'LogController') === false) {
                (new ActionLogModel())->insertOne($data);
            }
        } catch (\Throwable $e) {
        }

        return $response;
    }
}